package com.dhcc.bpm.modules.workflow.controller;

import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;

/**
 * @ClassName XmlData
 * @Description 连接工作流
 * @Author sjm
 * @Date 2020/3/3 0003 9:58
 * @Version V1.0
 * @Copyright: 2020 东华软件股份有限公司. All rights reserved.
 **/
@Component
public class XmlData {
    private static final Logger log = LoggerFactory.getLogger(XmlData.class);
    /** 工作流地址 */
    private static String Flow_Url;

    @Value("${workflow.flow-url}")
    public void setFlowUrl(String flowUrl) {
        Flow_Url = flowUrl;
    }

    /**
     * @Description xml报文
     * @Author sjm
     * @Date 20:50 2020/3/3 0003
     * @param path
     * @param postParameters
     * @return java.lang.String
     **/
    public static String getXml(String path, Map<String, Object> postParameters)throws IOException {
        //第一步：创建服务地址，不是WSDL地址
        //URL url = new URL("http://flowcenter.ceairtest.com/CeairDevService/ApiAuditNDC/ApiAuditNdcService.asmx/StartApiProSubChangeFlow");
        URL url = new URL(Flow_Url + path);
        //第二步：打开一个通向服务地址的连接
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        //第三步：设置参数
        //1发送方式设置：POST必须大写
        connection.setRequestMethod("POST");
        //2设置数据格式：content-type
        connection.setRequestProperty("content-type", "application/x-www-form-urlencoded");
        //  connection.setRequestProperty("content-type", "application/json");
        connection.setRequestProperty("Host", "flowcenter.ceairtest.com");
        //3设置输入输出，因为默认新创建的connection没有读写权限，
        connection.setDoInput(true);
        connection.setDoOutput(true);

        //第四步：组织SOAP数据，发送请求
//    File file = new File("G:\\桌面资料\\服务器.png");
//    String apiDoc = BinUtil.fileToBinStr(file);
//    System.out.print(apiDoc);

        String soapXML = "json=" + JSONObject.toJSONString(postParameters);
        //String soapXML = JSONObject.toJSONString(postParameters);
        log.info("json报文：" + soapXML);
        OutputStream os = connection.getOutputStream();
        os.write(soapXML.getBytes());

        //第五步：接收服务端响应，打印（xml格式数据）
        int responseCode = connection.getResponseCode();

        InputStream is = null;
        InputStreamReader isr = null;
        BufferedReader br = null;
        StringBuilder sb = null;
        String resData = "";
        try {
            is = connection.getInputStream();
            isr = new InputStreamReader(is);
            br = new BufferedReader(isr);

            sb = new StringBuilder();
            String temp = null;
            while(null != (temp = br.readLine())){
                sb.append(temp);
            }
            resData = sb.substring(sb.indexOf("{"), sb.lastIndexOf("}")+1);
            // System.out.println(sb.toString());
            log.info("返回信息：" + resData);
        } catch (Exception e) {
            log.error("xml报文异常：{}", e);
        } finally {
            if(br != null){
                br.close();
            }
            if(isr != null){
                isr.close();
            }
            if(is != null){
                is.close();
            }
        }
        os.close();
        return resData;
    }
}
